﻿using System;
using System.Net.Http.Headers;
using easyui.Models;
using Filters.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Filters
{
    public class ApiResultFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            
            base.OnActionExecuting(context);
            if (!context.ModelState.IsValid)
            {
                context.Result = new ValidationFailedResult(context.ModelState);
            }
            
        }
       
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            if (context.Result is ViewResult)
            { 
            }
            else
            {

                if (context.Result is BaseResultModel)
                {
                    context.Result = new ObjectResult(context.Result);
                }
                else if(context.Result is JsonResult json)
                {
                    context.Result = new ObjectResult(new BaseResultModel( code: StatusCodes.Status200OK, result:json.Value));
                }
                else if (context.Result is ObjectResult objectResult)
                {
                    context.Result = context.Result = new ObjectResult(new BaseResultModel(code: StatusCodes.Status200OK, result: objectResult.Value));
                }

            }
        }
    }
}
